﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NoORM.Core;
using NoORM.Core.Service;
using NoORM.Core.Contract;
using Microsoft.Extensions.Options;
using NoORM.Core.DbAcceess;

namespace Restsql.Api.Controllers
{
    /// <summary>
    /// 修改一行数据
    /// </summary>
    [Route("{database}/{table}.[controller]")]
    [ApiController]
    public class UpdateController : ControllerBase
    {
        /// <summary>
        /// 曾删改查的服务类对象
        /// </summary>
        private readonly CrudService service;

        /// <summary>
        /// 数据库连接字符串配置
        /// </summary>
        private readonly Dictionary<string, ConnectionStringConfig> configs;

        public UpdateController(IOptions<Dictionary<string, ConnectionStringConfig>> configsOption, CrudService service)
        {
            this.configs = configsOption.Value;
            this.service = service;
        }

        /// <summary>
        /// 修改一行数据
        /// </summary>
        /// <param name="database">数据库名</param>
        /// <param name="table">表名</param>
        /// <param name="request">sql请求</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Post(string database, string table, [FromBody] SqlRequest request)
        {
            
            ApiData<int> apiData = new ApiData<int>();
            apiData.ServerReceiveTime = DateTime.Now;
            var query = this.configs.Where(kv => kv.Key.Equals(database, StringComparison.CurrentCultureIgnoreCase));
            if (query == null || !query.Any())
            {
                apiData.Success = false;
                apiData.Message = "没有这个数据库";
                apiData.ServerSendTime = DateTime.Now;
                return new JsonResult(apiData);
            }
            if(request.Queries==null || !request.Queries.Any())
            {
                apiData.Success = false;
                apiData.Message = "服务器拒绝无条件的update指令";
                apiData.ServerSendTime = DateTime.Now;
                return new JsonResult(apiData);
            }

            ConnectionStringConfig config = query.First().Value;
            try
            {
                apiData.Data = await this.service.UpdateAsync(config, table,request);
                apiData.Success = apiData.Data > 0;
            }
            catch (Exception ex)
            {
                apiData.Success = false;
                apiData.Message = ex.Message;
            }
            apiData.ServerSendTime = DateTime.Now;
            return new JsonResult(apiData);
        }
    }
}
